package com.spring.cootask.web.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spera.shopoa.util.ShopOaSessionUtil;
import com.spring.cootask.web.model.CooTaskHead;
import com.spring.cootask.web.model.CooTaskTable;
import com.spring.cootask.web.model.CooTaskTrans;
import com.spring.cootask.web.model.CooTaskUser;
import com.spring.cootask.web.service.CooTaskService;
import com.spring.security.core.annotation.CheckParamterValidity;
import com.spring.security.core.annotation.OaRestPermission;
import com.spring.security.core.annotation.OaUserPermission;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.validators.Insert;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.Result;
import com.spring.tools.ValidatorResultHandler;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by WoJunyu on 2016/9/6.
 */
@Controller
@RequestMapping(value = "/cootask")
public class CooTaskController {
    @Resource
    private CooTaskService cooTaskService;

    /**
     * 发起人主页
     * @return
     */
    @OaUserPermission(value = "/cootask/createIndex")
    @RequestMapping(value = "/createIndex")
    public ModelAndView createIndex(Model model,HttpServletRequest request){
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        model.addAttribute("deptId",oaUser.getUser_shopdept_id());
        return new ModelAndView("main/cootask/task/create");
    }

    /**
     * 流转主页
     * @return
     */
    @OaUserPermission(value = "/cootask/transIndex")
    @RequestMapping(value = "/transIndex")
    public ModelAndView transIndex(Model model,HttpServletRequest request){
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        model.addAttribute("deptId",oaUser.getUser_shopdept_id());
        return new ModelAndView("main/cootask/task/trans");
    }

    /**
     * 流转明细主页
     * @param id  任务主键
     * @param request
     * @return
     */
    @OaUserPermission(value = "/cootask/transDetail")
    @RequestMapping(value = "/transDetail")
    public ModelAndView transDetail(@RequestParam String id,Model model,HttpServletRequest request){
        model.addAttribute("id",id);
        return new ModelAndView("main/cootask/task/transdetail");
    }

    //-------------------------------create start-----------------------

    /**
     * 发起人列表数据
     * @return
     */
    @CheckParamterValidity
    @RequestMapping(value = "/queryCreateTask")
    @ResponseBody
    public Object queryCreateTask(String page,String rows,CooTaskHead data,HttpServletRequest request) {
        Map<String, Object> retD = new HashMap<String, Object>();
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        //用户未登录
        if(oaUser!=null&&!ApplicationUtils.isNotNull(oaUser.getOa_user_id())){
            return null;
        }
        data.setCreateUserId(oaUser.getOa_user_id());
        try{
            PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));
            List<CooTaskHead> list = cooTaskService.selectCreateTaskByParm(data);
            PageInfo pageObj = new PageInfo(list);
            retD.put("total", pageObj.getTotal());
            retD.put("rows", list);
        }catch(Exception e){
            e.printStackTrace();
        }
        return retD;
    }

    /**
     * 修改或新增
     * @return
     */
    //@OaRestPermission(value="/cootask/saveTask")
	//@OaUserPermission(value="/cootask/saveTask")
    @RequestMapping(value = "/saveTask")
    @ResponseBody
    public Object saveTask(@RequestBody @Validated({Insert.class}) CooTaskHead data,BindingResult result,HttpServletRequest request) {
        Result retVal = ValidatorResultHandler.handle(result);
        if("0".equalsIgnoreCase(retVal.getStatus())){
            return retVal;
        }
        BaseResult ret = null;
        try {
            ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
            ret = cooTaskService.saveTask(data, oaUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "/deleteTask")
    @ResponseBody
    public Object deleteTask(String id) {
        BaseResult ret = null;
        try {
            ret = cooTaskService.deleteTask(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    //----------------------------create end-----------------------

    //----------------------------trans start-----------------------

    /**
     * 流转列表数据
     * @return
     */
    @RequestMapping(value = "/queryTransTask")
    @ResponseBody
    public Object queryTransTask(String page,String rows,CooTaskTrans data,HttpServletRequest request) {
        Map<String, Object> retD = new HashMap<String, Object>();
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        //用户未登录
        if(oaUser!=null&&!ApplicationUtils.isNotNull(oaUser.getOa_user_id())){
            return null;
        }
        data.setToUserId(oaUser.getOa_user_id());
        try{
            PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));
            List<CooTaskTrans> list = cooTaskService.selectTransTaskByParm(data);
            @SuppressWarnings({ "rawtypes", "unchecked" })
			PageInfo pageObj = new PageInfo(list);
            retD.put("total", pageObj.getTotal());
            retD.put("rows", list);
        }catch(Exception e){
            e.printStackTrace();
        }
        return retD;
    }

    /**
     * 下发
     * @return
     */
    @RequestMapping(value = "/saveTaskUser")
    @ResponseBody
    public Object saveTaskUser(@RequestBody @Validated({Insert.class}) CooTaskUser data,BindingResult result,HttpServletRequest request) {
        Result retVal = ValidatorResultHandler.handle(result);
        if("0".equalsIgnoreCase(retVal.getStatus())){
            return retVal;
        }
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        BaseResult ret = null;
        try {
            CooTaskUser upData = new CooTaskUser();
            upData.setId(data.getId());
            upData.setStatus(20);//上级已下发
            upData.setChangedtime(new Date());
            upData.setOperatorid(oaUser.getOa_user_id());
            upData.setOperatorname(oaUser.getOa_user_name());
            ret = cooTaskService.updateTaskUser(upData,oaUser);
            if("1".equals(ret.getStatus())){
                //下发
                data.setStatus(9);//下级未接收
                data.setPid(data.getId());
                ret = cooTaskService.saveTaskUser(data, oaUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "/backTaskUser")
    @ResponseBody
    public Object backTaskUser(String transId,String pid,HttpServletRequest request) {
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        BaseResult ret = null;
        try {
            CooTaskUser upData = new CooTaskUser();
            upData.setId(pid);
            upData.setStatus(-1);//上级状态退回
            upData.setChangedtime(new Date());
            upData.setOperatorid(oaUser.getOa_user_id());
            upData.setOperatorname(oaUser.getOa_user_name());
            ret = cooTaskService.updateTaskUser(upData,oaUser);
            if("1".equals(ret.getStatus())){
                //本级删除
                ret = cooTaskService.deleteTask(transId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 完结
     * @param id 流转主键
     * @param fTaskHeadid  任务主键
     * @param request
     * @return
     */
    @RequestMapping(value = "/finishTaskUser")
    @ResponseBody
    public Object finishTaskUser(@RequestParam String id,@RequestParam String fTaskHeadid,HttpServletRequest request) {
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        BaseResult ret = null;
        try {
            //流转完结
            CooTaskUser upData = new CooTaskUser();
            upData.setId(id);
            upData.setStatus(99);//完结
            upData.setChangedtime(new Date());
            upData.setOperatorid(oaUser.getOa_user_id());
            upData.setOperatorname(oaUser.getOa_user_name());
            ret = cooTaskService.updateTaskUser(upData,oaUser);
            if("1".equals(ret.getStatus())){//完结整个任务
                CooTaskHead head = new CooTaskHead();
                head.setId(fTaskHeadid);
                head.setTaskStatus(99);//完结
                ret = cooTaskService.saveTask(head, oaUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    //---------------------------trans end----------------------------


    //---------------------------transDetail start----------------------------

    /**
     * 流转明细数据（树形结构）
     * @return
     */
    @RequestMapping(value = "/queryTransDetail")
    @ResponseBody
    public Object queryTransDetail(String page,String rows,CooTaskTrans data,HttpServletRequest request) {
//        Map<String, Object> retD = new HashMap<String, Object>();
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        //用户未登录
        if(oaUser!=null&&!ApplicationUtils.isNotNull(oaUser.getOa_user_id())){
            return null;
        }
        //data.setToUserId(oaUser.getOa_user_id());
        List<CooTaskTrans> list = null;
        try{
            data.setIshead("yes");//是否查询任务头
            //PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));
            list = cooTaskService.selectTransTaskByParm(data);
            //PageInfo pageObj = new PageInfo(list);
            //retD.put("total", pageObj.getTotal());
           // retD.put("rows", list);
        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }

    //---------------------------transDetail start----------------------------
}
